﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using bmapi.Models.DataEntity;

namespace bmapi.Controllers
{
    public class CAD37Controller : CADFinishController
    {

        // POST: api/CAD37
        [HttpPost, Route("cad37/Finish")]
        public string Finish(dynamic json)
        {            
            WriteDebug("cad37/Finish", "进入37");
            if (json == null)
                return ReturnError(201, "参数不能为空");
            int uid = GetCrrentIDByToken();
            PC pc = GetPC(Convert.ToInt32(json.id));
            if (pc == null)
                return ReturnError(201, "流程不存在");

            List<SQLCommand> cmds = new List<SQLCommand>();
            XmlDocument doc = new XmlDocument();
            //xml文件路径
            string pcPath = GetPCPath(pc.pc_id);
            string xmlpath = pcPath+"\\"+pc.path+".bom";
            doc.Load(xmlpath); 
            int minlsh = 0;
            //获取LSH节点列表 
            XmlNodeList lshparam = doc.GetElementsByTagName("param");
            if (lshparam.Count > 0)
                cmds.AddRange(UpdateLSH(lshparam, pc.pc_id, ref minlsh));
            else
            {
                WriteDebug("cad37/Finish", "不存在LSH节点列表");
                return ReturnError(201, "不存在LSH节点列表");
            }
            //修改Order_tb  获取面料用量  由于xml文件中是bomlist集合  故按有多个bom来处理  增加代码的扩展性
            XmlNodeList boms = doc.GetElementsByTagName("bom");
            if (boms.Count > 0)               
                cmds.AddRange(UpdateOrder(boms, pc.pc_id, minlsh));
            else
                WriteDebug("cad37/Finish", "不存在bomlist集合");
            //获取bed节点列表
            XmlNodeList bedList = doc.GetElementsByTagName("bed");
            if (bedList.Count > 0)
                cmds.AddRange(AddBed(uid, pc, bedList));
            else
            {
                WriteDebug("cad37/Finish", "不存在bed节点列表");
                return ReturnError(201, "不存在bed节点列表");
            }
            try
            {
                int rtn = SQLCommand.ExecTran(cmds);
                if (rtn == 1)
                {
                    WriteDebug("cad37/Finish", "数据更新成功，开始移动文件夹");
                    //将cut文件移动到buyiCut文件夹下 
                    string cutPath = m_buyiRoot + "\\buyiCut\\" + pc.path;
                    string sourcePath = pcPath + "\\cut";
                    MoveCut(sourcePath, cutPath,pc);
                    return ReturnError(200, "OK");
                }
                else
                {
                    WriteDebug("cad37/Finish", "数据更新失败");
                    return ReturnError(201, "数据更新失败");
                }
            }
            catch (Exception e)
            {
                WriteDebug("cad37/Finish", "数据更新失败,"+e.Message);
                return ReturnError(201, "数据更新失败");
            } 
        }

        /// <summary>
        /// 移动cut文件目录 
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="cutPath"></param>
        private void MoveCut(string sourcePath, string cutPath,PC pc)
        {
            if (!Directory.Exists(sourcePath))
                WriteDebug("MoveCut", "不存在目录," + sourcePath);
            else
            {
                if (Directory.Exists(cutPath))
                {
                    //删除文件目录 
                    Directory.Delete(cutPath, true);
                    Directory.Move(sourcePath, cutPath);                    
                }
                else
                    Directory.Move(sourcePath, cutPath);
                //37完成删除PC_tb记录改变Order_tb状态,移动文件目录
                string pcPath = GetPCPath(pc.pc_id);
                Finish37(pc, pcPath);
            }
        }
        /// <summary>
        /// 37的完成处理
        /// </summary>删除PC_tb记录改变Order_tb状态,移动文件目录到history
        /// <param name="pc"></param>
        /// <param name="pcPath"></param>
        private void Finish37(PC pc,string pcPath)
        {
            try
            {
                List<SQLCommand> cmds = new List<SQLCommand>();
                SQLCommand sc = null;
                string sql = "delete PC_tb where pc_id=@pcid";
                sc = new SQLCommand(sql, "@pcid", pc.pc_id);
                cmds.Add(sc);
                sql = "update Order_tb set state=2 where id=@orderid";
                sc = new SQLCommand(sql, "@orderid", pc.pc_id);
                cmds.Add(sc);
                int rtn = SQLCommand.ExecTran(cmds);
                if (rtn == 1)
                {
                    WriteDebug("Finish37", "成功删除PC以及修改order状态,开始移动文件夹");
                    string hispath = GetHistoryPath(pc.pc_id);
                    Directory.Move(pcPath, hispath + "\\" + pc.path);
                    WriteDebug("Finish37", "成功");
                }
            }
            catch (Exception e)
            {
                WriteDebug("Finish37", "失败,"+e.Message);
            }
           
        }

        /// <summary>
        /// 修改流水号
        /// </summary>
        /// <param name="lshparam"></param>
        /// <param name="orderid"></param>
        /// <returns></returns>
        private List<SQLCommand> UpdateLSH(XmlNodeList lshparam,int orderid,ref int minLsh)
        {
            string sql = "update LSH_tb set LSH=@lsh where order_id=@orderid and erp_id=@erpid";
            List<SQLCommand> cmds = new List<SQLCommand>();
            
            for (int i = 0; i < lshparam.Count; i++)
            {
                int erpid = 0;
                int lsh = 0;
                SQLCommand sc = new SQLCommand(sql);
                foreach (XmlNode item in lshparam[i])
                {
                    if (item.Name.Equals("name"))
                        if (item.InnerText != null)
                            erpid = Convert.ToInt32(item.InnerText);
                    if (item.Name.Equals("val"))
                        if (item.InnerText != null)
                            lsh = Convert.ToInt32(item.InnerText);
                }
                //获取最小流水号 因为要去最小流水号  所以就没有使用xml节点取值的函数 
                if (i == 0)
                    minLsh = lsh;
                else
                {
                    if (lsh < minLsh)
                        minLsh = lsh;
                }                      
                
                sc.Add("@lsh", lsh);
                sc.Add("@orderid", orderid);
                sc.Add("@erpid", erpid);
                cmds.Add(sc);
            }
            return cmds;
        }
        /// <summary>
        /// 修改Order表中的物料用量 以及流水号  流水号取最小值
        /// </summary>
        /// <param name="boms"></param>
        /// <param name="orderid"></param>
        /// <returns></returns>
        private List<SQLCommand> UpdateOrder(XmlNodeList boms,int orderid,int minlsh)
        {
           
            List<SQLCommand> cmds = new List<SQLCommand>();
            string sql = "update Order_tb set m_dose=@mdose,LSH=@lsh where id=@orderid mCode=@mcode";
            for (int i = 0; i < boms.Count; i++)
            {
                SQLCommand sc = new SQLCommand(sql);
                foreach (XmlNode item in boms[i])
                {
                    if (item.Name.Equals("val"))
                        AddInt(sc, "@mdose", item);
                    if (item.Name.Equals("name"))
                        AddString(sc, "@mcode", item);
                }
                sc.Add("@lsh", minlsh);
                sc.Add("@orderid", orderid);
                cmds.Add(sc);
            }
            return cmds;
        }
        /// <summary>
        /// 新增床信息
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pc"></param>
        /// <param name="doc"></param>
        private List<SQLCommand> AddBed(int uid, PC pc, XmlNodeList beds)
        {
            try
            {
                List<SQLCommand> cmds = new List<SQLCommand>();
                string sql = "insert into Bed_tb(id,PLID,order_id,type,name,material_name,material_code,lay_plan,lay_len,cut_len,lay_count,Lsh1,Lsh2,uc,width) values(@id,@PLID,@order_id,@type,@name,@material_name,@material_code,@lay_plan,@lay_len,@cut_len,@lay_count,@lsh1,@lsh2,@uc,@width)";
                //流程路径
                string pcPath = GetPCPath(pc.pc_id) + "\\cut\\";

                for (int i = 0; i < beds.Count; i++)
                {
                    string bedpath = pcPath + beds[i]["name"].InnerText + ".nc";
                    if (!File.Exists(bedpath))
                    {
                        WriteDebug("AddBed", "bedpath:" + bedpath + "不存在");
                        continue;
                    }
                    WriteDebug("AddBed", "bedpath:" + bedpath + "存在");
                    SQLCommand sc = new SQLCommand(sql);
                    foreach (XmlNode node in beds[i])
                        AddBed(node, sc);

                    int bid = GetNewSafeID(uid);

                    sc.Add("@id", bid);
                    sc.Add("@PLID", pc.PLID);
                    sc.Add("@order_id", pc.pc_id);

                    cmds.Add(sc);
                }
                WriteDebug("AddBed", "bed插入语句完成,共" + cmds.Count + "条语句");
                return cmds;
            }
            catch (Exception e)
            {
                WriteDebug("AddBed", "异常:"+ e.Message);
                throw;
            }
           
        }
        private void AddBed(XmlNode node, SQLCommand sc)
        {
            if (node.Name == "type")
            {
                AddInt(sc, "@type", node);
            }
            else if (node.Name == "name")
            {
                AddString(sc, "@name", node);
            }
            else if (node.Name.Equals("typeName"))
            {
                AddString(sc, "@material_name", node);
            }
            else if (node.Name.Equals("code"))
            {
                AddString(sc, "@material_code", node);
            }
            else if (node.Name.Equals("color"))
            {
                AddString(sc, "@lay_plan", node);
            }
            else if (node.Name.Equals("len"))
            {
                AddDouble(sc, "@lay_len", node);
            }
            else if (node.Name.Equals("cutLen"))
            {
                AddDouble(sc, "@cut_len", node);
            }
            else if (node.Name.Equals("layCount"))
            {
                AddDouble(sc, "@lay_count", node);
            }
            else if (node.Name.Equals("lsh1"))
            {
                AddInt(sc, "@lsh1", node);
            }
            else if (node.Name.Equals("lsh2"))
            {
                AddInt(sc, "@lsh2", node);
            }
            else if (node.Name.Equals("uc"))
            {
                AddDouble(sc, "@uc", node);
            }
            else if (node.Name.Equals("width"))
            {
                AddDouble(sc, "@width", node);
            }
        }
    }
}
